<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
      :inline="true"
    >
      <el-form-item label="资产分类" prop="assetType" style="width: 41.4%">
        <el-select
          v-model="formData.assetType"
          placeholder="请选择资产分类"
          style="width: 100%"
          :disabled="formType == 'update'"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.ASSET_CLASSIFICATION)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="条码编号" prop="barcodeNumber">
        <el-input
          v-model="formData.barcodeNumber"
          placeholder="请输入条码编号"
          disabled
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="资产编号" prop="assetNumber">
        <el-input v-model="formData.assetNumber" placeholder="请输入资产编号" style="width: 100%" />
      </el-form-item>
      <el-form-item label="资产名称" prop="title">
        <el-input v-model="formData.title" placeholder="请输入资产名称" />
      </el-form-item>
      <el-form-item label="品牌" prop="brand">
        <el-input v-model="formData.brand" placeholder="请输入品牌" />
      </el-form-item>
      <el-form-item label="规格型号" prop="specificationModel">
        <el-input v-model="formData.specificationModel" placeholder="请输入规格型号" />
      </el-form-item>
      <el-form-item label="数量" prop="number">
        <el-input v-model="formData.number" placeholder="请输入数量" />
      </el-form-item>
      <el-form-item label="计量单位" prop="unitOfMeasurement">
        <el-select
          v-model="formData.unitOfMeasurement"
          placeholder="请选择计量单位"
          style="width: 200px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.UNIT_OF_MEASUREMENT)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="资产原值" prop="originalValue">
        <el-input-number
          style="width: 100%"
          v-model="formData.originalValue"
          precision="2"
          :min="0"
          placeholder="请输入资产原值"
        />
      </el-form-item>
      <el-form-item label="生产时间" prop="obtainTime">
        <el-date-picker
          v-model="formData.obtainTime"
          type="date"
          value-format="x"
          placeholder="选择生产时间"
        />
      </el-form-item>
      <el-form-item label="管理部门" prop="managementDept">
        <el-tree-select
          v-model="formData.managementDept"
          :data="deptList"
          check-strictly
          style="width: 190px"
        />
      </el-form-item>
      <el-form-item label="管理人" prop="managementUser">
        <el-select
          v-model="formData.managementUser"
          placeholder="请选择管理人"
          style="width: 200px"
        >
          <el-option
            v-for="dict in managerUserAllList"
            :key="dict.id"
            :label="dict.nickname"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="使用部门" prop="useDept">
        <el-tree-select
          v-model="formData.useDept"
          :data="deptList"
          check-strictly
          style="width: 190px"
        />
      </el-form-item>
      <el-form-item label="使用人" prop="useUser">
        <el-select v-model="formData.useUser" placeholder="请选择使用人" style="width: 200px">
          <el-option
            v-for="dict in useUserAllList"
            :key="dict.id"
            :label="dict.nickname"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="存放地点" prop="storageLocation">
        <el-input v-model="formData.storageLocation" placeholder="请输入存放地点" />
      </el-form-item>
      <el-form-item label="业务状态" prop="businessStatus">
        <el-radio-group v-model="formData.businessStatus">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.BUSINESS_STATUS)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="成新率" prop="newnessRate">
        <el-select v-model="formData.newnessRate" placeholder="请选择成新率" style="width: 200px">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.NEWNESS_RATE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="财务记账日期" prop="financialAccountingTime">
        <el-date-picker
          v-model="formData.financialAccountingTime"
          type="date"
          value-format="x"
          placeholder="选择财务记账日期"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark" style="width: 100%">
        <el-input v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>
      <el-form-item label="图片" prop="files" style="width: 100%">
        <UploadImgs v-model="formData.files" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="paste" type="primary">粘 贴</el-button>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { ManagerApi, ManagerVO } from '@/api/asset/manager'
import { getSimpleDeptList } from '@/api/system/dept'
import { getUserPage } from '@/api/system/user'

/** 资产管理 表单 */
defineOptions({ name: 'ManagerForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  assetNumber: undefined,
  barcodeNumber: undefined,
  title: undefined,
  assetType: undefined,
  brand: undefined,
  specificationModel: undefined,
  number: undefined,
  unitOfMeasurement: undefined,
  originalValue: undefined,
  obtainTime: undefined,
  managementDept: undefined,
  managementUser: undefined,
  useDept: undefined,
  useUser: undefined,
  storageLocation: undefined,
  businessStatus: undefined,
  newnessRate: undefined,
  financialAccountingTime: undefined,
  remark: undefined
})
const formRules = reactive({
  barcodeNumber: [{ required: true, message: '条码编号不能为空', trigger: 'blur' }],
  title: [{ required: true, message: '资产名称不能为空', trigger: 'blur' }],
  assetType: [{ required: true, message: '资产分类不能为空', trigger: 'change' }],
  useDept: [{ required: true, message: '使用部门不能为空', trigger: 'blur' }],
  useUser: [{ required: true, message: '使用人不能为空', trigger: 'blur' }],
  storageLocation: [{ required: true, message: '存放地点不能为空', trigger: 'blur' }],
  businessStatus: [{ required: true, message: '业务状态不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

const deptList = ref([])
const useUserAllList = ref([])
const managerUserAllList = ref([])

watch(
  () => formData.value.useDept,
  async (deptId) => {
    const ret = await getUserPage({ pageSize: 1000, deptId })
    useUserAllList.value = ret.list
  }
)

watch(
  () => formData.value.managementDept,
  async (deptId) => {
    const ret = await getUserPage({ pageSize: 1000, deptId })
    managerUserAllList.value = ret.list
  }
)

watch(
  () => formData.value.assetType,
  async (assetType) => {
    if (!assetType) {
      return
    }
    if (formType.value === 'create') {
      formData.value.barcodeNumber = await ManagerApi.getBarcodeNumber(assetType)
    }
  }
)

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  getDeptList()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await ManagerApi.getManager(id)
      formData.value = {
        ...data,
        files: data.files ? JSON.parse(data.files).map((v) => v.url) : []
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const paste = () => {
  const copy_edit = localStorage.getItem('copy_edit')
  if (!copy_edit) {
    message.warning('没有可粘贴内容!')
    return
  }
  const d = JSON.parse(copy_edit)
  const data = formData.value

  const e = {}
  for (const datum in data) {
    if (data[datum] == null || data[datum] == undefined || data[datum] == "") {
      e[datum] = d[datum]
    }
  }

  formData.value = { ...data, ...e }
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ManagerVO
    const dataParams = { ...data }
    if (data.files) {
      dataParams.files = JSON.stringify(
        data.files.map((v) => {
          return {
            url: v || v.url
          }
        })
      )
    }
    if (formType.value === 'create') {
      await ManagerApi.createManager(dataParams)
      message.success(t('common.createSuccess'))
    } else {
      await ManagerApi.updateManager(dataParams)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    assetNumber: undefined,
    barcodeNumber: undefined,
    title: undefined,
    assetType: undefined,
    brand: undefined,
    specificationModel: undefined,
    number: undefined,
    unitOfMeasurement: undefined,
    originalValue: undefined,
    obtainTime: undefined,
    managementDept: undefined,
    managementUser: undefined,
    useDept: undefined,
    useUser: undefined,
    storageLocation: undefined,
    businessStatus: undefined,
    newnessRate: undefined,
    financialAccountingTime: undefined,
    remark: undefined,
    files: []
  }
  formRef.value?.resetFields()
}

const listToTree = (data, parentId = 0) => {
  const tree = []
  for (const item of data) {
    if (item.parentId === parentId) {
      const children = listToTree(data, item.id)
      if (children.length) {
        item.children = children
      }
      tree.push({ ...item, label: item.name, value: item.id })
    }
  }
  return tree
}

const getDeptList = async () => {
  const ret = await getSimpleDeptList()
  deptList.value = listToTree(ret)
}
</script>
